package cn.tjad.tjad2.module.document.fragment;

import android.app.Dialog;
import android.content.pm.ActivityInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.View;

import com.hjy.http.download.FileDownloadInfo;
import com.qiandian.android.base.common.bean.CommonBean;
import com.qiandian.android.base.common.utils.UrlUtils;
import com.qiandian.android.base.net.http.HttpConstants;
import com.qiandian.android.base.net.http.HttpId;
import com.qiandian.android.base.net.http.IDataCallBack;
import com.qiandian.android.base.widget.TJADTTitleView;

import java.io.File;

import cn.tjad.tjad2.application.TjadApplication;
import cn.tjad.tjad2.business.RemoteDataService;
import cn.tjad.tjad2.consts.TjadConsts;
import cn.tjad.tjad2.consts.UrlConsts;
import cn.tjad.tjad2.data.bean.Document;
import cn.tjad.tjad2.net.TjadHttpServer;
import cn.tjad.tjad2.utils.FileHandler;
import cn.tjad.tjad2.utils.FileHelper;
import cn.tjad.tjad2.utils.NetworkUtils;
import cn.tjad.tjad2.utils.Tools;
import cn.tjad.tjad2.utils.ZipUtils;
import cn.tjad.tjad2.module.web.WebViewFragment;
import cn.tjad.tjad2.module.common.dialog.OnDialogClickListener;
import cn.tjad.tjad2.module.common.dialog.TjDialogFragment;

public class ModelFragment extends WebViewFragment implements IDataCallBack, FileHandler.OnFileDownloadListener {

    private FileHandler fileHandler;
    private int projectId;

    private Document document;

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
    }

    @Override
    protected boolean showTitle() {
        return false;
    }

    @Override
    protected void setCustomerTitle(TJADTTitleView titleView) {
        titleView.setCenterText("模型");
        titleView.showLeft(false);
        titleView.showRight(true);
        titleView.setRightText("刷新");
    }

    @Override
    public void onTitleClick(int which) {
        super.onTitleClick(which);
        switch (which) {
            case TJADTTitleView.TITLE_RIGHT:
                loadPage();
                break;
        }
    }

    @Override
    protected void loadPage() {
        projectId = TjadApplication.getInstance().getSession().getProjectId();
        RemoteDataService.getModel(projectId, this);
    }

    @Override
    public boolean onReceiveError(int httpId, int errorCode, String errorMsg) {
        if (httpId == HttpId.MODEL) {
            Tools.showToast(errorMsg);
        }
        return false;
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
            getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        } else {
            getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        } else {
            getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        }
    }

    @Override
    public void onDataRefresh(int httpId, Object responseBean) {
        CommonBean<Document> bean = (CommonBean<Document>) responseBean;
        if (bean.resCode == HttpConstants.CODE_SUCCESS) {
            Document doc = bean.result;
            if (doc == null) {
                TjDialogFragment.Builder builder = new TjDialogFragment.Builder(getContext());
                builder.setTitle("错误提示")
                        .setMessage("该项目未设置首页模型， 请到网页版设置")
                        .setNegativeButton("我知道了", null)
                        .show(getChildFragmentManager());

            } else {
                this.document = doc;
                if ("0".equals(doc.forgeStatus)) {
                    loadModel(doc);
                }
            }
        } else {
            TjDialogFragment.Builder builder = new TjDialogFragment.Builder(getContext());
            builder.setTitle("错误提示")
                    .setMessage("该项目未设置首页模型， 请到网页版设置")
                    .setNegativeButton("我知道了", null)
                    .show(getChildFragmentManager());
        }
    }

    //先判断有没有缓存模型, 如果有, 直接加在离线
    //否则, 先加载在线模型, 同时下载缓存
    private void loadModel(final Document document) {
        if (document == null) {
            return;
        }
        final String local = TjadConsts.UNZIP_DOCUMENT + "/" + document.name;
        final String source = TjadConsts.DOWNLOAD_FILE + "/" + document.name + ".zip";
        File localFile = new File(local);
        File sourceFile = new File(source);
        if (localFile.exists()) {
            openOffline(local);
        } else if (sourceFile.exists()) {
            openWhenUnzip(source, local);
        } else {
            TjDialogFragment.Builder builder = new TjDialogFragment.Builder(getContext());
            builder.setTitle("请选择")
                    .setMessage("在线浏览还是下载离线模型?")
                    .setNegativeButton("在线浏览", new OnDialogClickListener() {
                        @Override
                        public boolean onClick(Dialog dialogInterface, int i) {
                            viewOnlineFileWithNetStatus(document);
                            return true;
                        }
                    })
                    .setPositiveButton("离线下载", new OnDialogClickListener() {
                        @Override
                        public boolean onClick(Dialog dialogInterface, int i) {
//                            Tools.showToast("正在下载离线文件...");
                            String url = UrlUtils.getUrl(UrlConsts.DOCUMENT_DOWNLOAD_URL, String.valueOf(document.id));
                            if (fileHandler == null) {
                                fileHandler = new FileHandler(getContext());
                            }
                            fileHandler.downloadFileWithCheck(getContext(), url, document.name + ".zip",ModelFragment.this);
                            return true;
                        }
                    })
                    .show(getChildFragmentManager());

        }
    }

    private void viewOnlineFileWithNetStatus(final Document document) {
        if (!NetworkUtils.isNetworkConnected(getContext())) {
            Tools.showToast("网络连接失败, 请检查网络!");
            return;
        }
        if (!NetworkUtils.isWifi(getContext())) {
            TjDialogFragment.Builder builder = new TjDialogFragment.Builder(getContext());
            builder.setTitle("提示")
                    .setMessage("您当前为非WIFI网络, 是否继续?")
                    .setPositiveButton("继续", new OnDialogClickListener() {
                        @Override
                        public boolean onClick(Dialog dialogInterface, int i) {
                            viewOnlineFile(document);
                            return true;
                        }
                    })
                    .setNegativeButton("取消", null)
                    .show(getChildFragmentManager());
        } else {
            viewOnlineFile(document);
        }
    }

    //预览在线文件
    private void viewOnlineFile(Document document) {
        if (document == null) {
            return;
        }
        if ("0".equals(document.forgeStatus)) {
            String localPath = TjadConsts.APPHTML;
            int id = document.id;
            String token = TjadApplication.getInstance().getSession().getToken();
            String url = UrlUtils.getUrl(UrlConsts.REMOTE_DOCUMENT_PREVIEW_URL, "" + TjadHttpServer.PORT, localPath,
                    String.valueOf(projectId), token, String.valueOf(id));
            webView.loadUrl(url);
//            Bundle bundle = new Bundle();
//            bundle.putString("url", url);
//            RouteUtils.toPage(getContext(), PageId.LAND_WEBVIEW, bundle);
        }
    }

//    private void downloadOrViewFile(Document document) {
//        docId = document.id;
//        final String localFile = TjadConsts.UNZIP_DOCUMENT + "/" + document.name;
//        final String sourceFile = TjadConsts.DOWNLOAD_FILE + "/" + document.name + ".zip";
//        final File file = new File(localFile);
//        if (file.exists()) {
//            openOffline(localFile);
//        } else if (new File(sourceFile).exists()) {
//            openWhenUnzip(sourceFile, localFile);
//        } else {
//            Tools.showToast("正在下载离线文件...");
//            String url = UrlUtils.getUrl(UrlConsts.DOCUMENT_DOWNLOAD_URL, String.valueOf(docId));
//            if (fileHandler == null) {
//                fileHandler = new FileHandler(getContext());
//            }
//            fileHandler.downloadFileWithCheck(getContext(), url, document.name + ".zip",this);
//        }
//    }

    private void openOffline(String localFile) {
        String token = TjadApplication.getInstance().getSession().getToken();
        String url = UrlUtils.getUrl(UrlConsts.LOCAL_DOCUMENT_PREVIEW_URL, "" + TjadHttpServer.PORT, TjadConsts.APPHTML,
                localFile, token, projectId + "");
        webView.loadUrl(url);
    }

    private void openWhenUnzip(String sourceFile, String localFile) {
        new AsyncTask<String, Void, String>() {

            @Override
            protected void onPreExecute() {
                Tools.showToast("正在解压文件, 解压完成后打开");
            }

            @Override
            protected String doInBackground(String... args) {
                String source = args[0];
                String dest = args[1];
                String destFile = null;
                try {
                    destFile = ZipUtils.unzipAndRenameFolder(source, dest);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return destFile;
            }

            @Override
            protected void onPostExecute(String s) {
                if (s == null) {
                    Tools.showToast("解压文件发生异常, 无法打开文件");
                }
                openOffline(s);
            }
        }.execute(sourceFile, localFile);
    }

    @Override
    public void onProgress(FileDownloadInfo fileUploadInfo, long totalSize, long currSize, int progress) {

    }

    @Override
    public void onSuccess(final FileDownloadInfo fileDownloadInfo) {
        openWhenUnzip(fileDownloadInfo.getOutFile().getPath(), TjadConsts.UNZIP_DOCUMENT);
    }

    @Override
    public void onFailed(FileDownloadInfo fileUploadInfo, int errorType, String errorMsg) {
        TjDialogFragment.Builder builder = new TjDialogFragment.Builder(getContext());
        builder.setMessage("出错提示")
                .setMessage("离线文件下载失败, 重新下载离线文件，还是浏览在线模型？")
                .setPositiveButton("重新下载", new OnDialogClickListener() {
                    @Override
                    public boolean onClick(Dialog dialogInterface, int i) {
                        String localFile = TjadConsts.UNZIP_DOCUMENT + "/" + document.name;
                        String sourceFile = TjadConsts.DOWNLOAD_FILE + "/" + document.name + ".zip";
                        FileHelper.deleteFile(localFile);
                        FileHelper.deleteFile(sourceFile);
                        if (document == null) {
                            loadPage();
                        } else {
                            loadModel(document);
                        }
                        return true;
                    }
                })
                .setNeutralButton("在线浏览", new OnDialogClickListener() {
                    @Override
                    public boolean onClick(Dialog dialogInterface, int i) {
                        return true;
                    }
                })
                .setNegativeButton("取消", null)
                .show(getChildFragmentManager());
    }
}
